﻿<head>
    <title>获取文字点阵示例</title>
    <style>
        #editor {
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <textarea id="editor">
    </textarea>
    <script>
        var text2points = function(){
        };
        (function(){
            function format(template, json){
                if (!json) 
                    return template;
                return template.replace(/#\{(.+?)\}/g, function(){
                    return json[arguments[1]];
                });
            }
            var canvas = document.createElement("canvas");
            if (!canvas || !canvas.getContext) 
                return;
            var context = canvas.getContext('2d');
			/**
			 * 文字转换成点阵
			 * @param {String} text
			 * @param {Object} options
			 * 	{Integer} width 宽度
			 *  {Integer} height 高度
			 *  {Object} data 点阵 通过["x,y"]访问
			 */
            text2points = function(text, options){
                if (!text) 
                    return;
                options = options || {};
                options.size = options.size || 12;
                options.name = options.name || "sans-serif";
                // 绘制文字
                var font = format('#{size}px #{name}', options);
                context.font = font;
                canvas.width = context.measureText(text).width;
                canvas.height = options.size;
				context.clearRect(0, 0, canvas.width, canvas.height);
                context.font = font;
                context.textAlign = 'left';
                context.textBaseline = 'top';
                context.fillText(text, 0, 0);
                
                var data = context.getImageData(0, 0, canvas.width, canvas.height).data, p = 0, results = {
                    width: canvas.width,
                    height: canvas.height,
                    data: {}
                };
                for (var y = 0, h = results.height; y < h; y++) {
                    for (var x = 0, w = results.width; x < w; x++) {
                        if (data[p + 3]) 
                            results.data[[x, y]] = true;
                        p += 4;
                    }
                }
                return results;
            }
        })();
        
        (function(){
            var editor = document.getElementById("editor");
            var points = text2points("打酱油");
            var lines = [];
            for (var y = 0; y < points.height; y++) {
                for (var x = 0; x < points.width; x++) {
                    lines.push(points.data[[x, y]] ? "■" : "□");
                }
                lines.push("\n");
            }
            editor.value = lines.join("");
        })();
    </script>
</body>
